import dayjs from 'dayjs';

const prefix = `__SV`;
// const prefix = `__SV_${import.meta.env.VITE_APP_VERSION}`;

const getFullKey = (key: string) => `${prefix}_${key}`;

/**
 * 写缓存
 */
export function setCache<T = any>(key: string, item: T) {
    localStorage.setItem(
        getFullKey(key),
        JSON.stringify({
            t: dayjs().format('YYYYMMDDHHmmssSSS'),
            data: item,
        }),
    );
}

/**
 * 获取缓存内容
 * `null` 没有缓存
 */
export function getCache<T = any>(key: string) {
    const cacheContent = localStorage.getItem(getFullKey(key));
    if (cacheContent) {
        return JSON.parse(cacheContent).data as T;
    }
    return null;
}

/**
 * 删除缓存
 */
export function removeCache(key: string) {
    localStorage.removeItem(getFullKey(key));
}
